﻿'use strict';

app.service('$ListDataService', function ($q, $http, SPHandy) {
    
    function postProcessTaskResults(data, status, headers, config) {
        //This is a simple example of post processing data returned from a web service,
        //Most times I've needed to do this so even though you dont necesarily need to
        //Im doing it here for example

        var tasks = [];

        angular.forEach(data.d.results, function (taskItem) {
            tasks.push({
                ID: taskItem.ID,
                Title: taskItem.Title,
                Description: taskItem.Body,
                IsDirty: false
            });
        })

        return tasks;
    }


    this.getItemsNew = function ($scope) {
        //Im post processign here so need to create a promise rather than get http to return one.
        //Besides this is normal the amount of post processing I've seen in Controller examples
        //manipulating returned data is scary its not supposed to be like that.
        var deferred = $q.defer();
        var url = $scope.appWebUrl + "/_api/web/lists/getByTitle('Tasks')/items?$select=ID,Title,Body";
        $http({
            method: 'GET',
            url: url,
            headers: { "Accept": "application/json; odata=verbose" }
        })
            .success(function (data, status, headers, config) {
                deferred.resolve(postProcessTaskResults(data, status, headers, config));
            })
            .error(function (data, status, headers, config) {
                console.log("Error " + status);
                deferred.reject(status);
            });
        return deferred.promise;
    };


    //This is an example of doing it the Old way with WebServices
    //Its not restful, its XML so $http cant format the post properly
    //so we have to resort to old style ajax post instead.
    this.getItems = function ($scope) {

        var listContents;
        var deferred = $q.defer();

        //This is lovely why would anyone want to use REST :-)
        var soapEnv = "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema'> \
	    				<soap:Body><GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'> \
	    					<listName>Tasks</listName> \
	    					<query><Query xmlns=''> \
	    						<OrderBy><FieldRef Name='Title' /></OrderBy></Query></query> \
	    					<viewFields><ViewFields xmlns='' > \
	    						<FieldRef Name='ID' /> \
	    						<FieldRef Name='Title' /> \
	    						<FieldRef Name='Body' /> \
	    					</ViewFields> \
	    					</viewFields> \
	    					 <rowLimit>0</rowLimit> \
	    					<queryOptions><QueryOptions xmlns='' /></queryOptions></GetListItems></soap:Body></soap:Envelope>";

        $.ajax({
            url: "../_vti_bin/lists.asmx",
            type: "POST",
            dataType: "xml",
            data: soapEnv,
            contentType: "text/xml; charset=\"utf-8\""
        })
	    	.done(function (xmlResponse) {

	    	    //This next function getZRows is taken from SPServices, so if you are accesing old SPLists
	    	    //via the webserice dont do it like this use SPServices the hard stuffs been done for you.
	    	    //This example is here to demonstrate calling a WebService,  if the service you call
	    	    //Is CORS compliant of course or your on premise calling one of your own you installed in _layouts
                //In which case this processing of the xmlResponse would be very different.
	    	    var domElementArray = SPHandy.getZRows(xmlResponse);

	    	    //The map function is a technique for processing one array and returning another
	    	    //jQuery array, in this case we are returning an array of jscript objects that map to attributes
	    	    //of the XML entries.
	    	    //see http://api.jquery.com/jQuery.map/
	    	    var dataMap = domElementArray.map(function () {
	    	        return {
	    	            ID: $(this).attr('ows_ID'),
	    	            Title: $(this).attr('ows_Title'),
	    	            Description: $(this).attr('ows_Body'),
	    	            IsDirty: false
	    	        };
	    	    });

	    	    //In this case the autocomplete function cannot handle jQuery arrays it want POJ arrays in a specific format.
	    	    //By using the get() function we return the internals of the jQuery array the core objects
	    	    //see http://api.jquery.com/get/
	    	    listContents = dataMap.get();


	    	    //When not using $http  angular is not in control so when we are done fetching
	    	    //its at this point we do the $scope.$apply   
	    	    //Do it back in the controller and you will have digest issue and you 
	    	    //will start using the antipattern of checking the digest is in process.
	    	    $scope.$apply(deferred.resolve(listContents));

	    	})
	    	.fail(function () {
	    	    //Same applies here
	    	    $scope.$apply(deferred.reject());
	    	});


        return deferred.promise;
    };



});

